//! 示例数据填充功能
//! 提供用于测试和演示的示例数据

use crate::client::EntityClient;
use crate::models::party::*;
use crate::models::party_relationship::*;
use crate::models::contact::*;
use crate::services::*;
use crate::{Result, PartyModError};
use chrono::{DateTime, Utc};
use std::collections::HashMap;

/// 示例数据管理器
pub struct SampleDataManager {
    client: EntityClient,
    party_service: PartyService,
    organization_service: OrganizationService,
    customer_service: CustomerService,
    contact_service: ContactService,
}

impl SampleDataManager {
    /// 创建新的示例数据管理器
    pub fn new(client: EntityClient) -> Self {
        let party_service = PartyService::new(client.clone());
        let organization_service = OrganizationService::new(client.clone());
        let customer_service = CustomerService::new(client.clone());
        let contact_service = ContactService::new(client.clone());
        
        Self {
            client,
            party_service,
            organization_service,
            customer_service,
            contact_service,
        }
    }

    /// 加载所有示例数据
    pub async fn load_all_sample_data(&mut self) -> Result<()> {
        println!("开始加载示例数据...");
        
        // 1. 加载基础数据类型
        self.load_basic_types().await?;
        println!("✓ 基础数据类型加载完成");
        
        // 2. 创建示例组织
        let company_ids = self.create_sample_companies().await?;
        println!("✓ 示例公司创建完成: {:?}", company_ids);
        
        // 3. 创建示例个人
        let person_ids = self.create_sample_persons().await?;
        println!("✓ 示例个人创建完成: {:?}", person_ids);
        
        // 4. 建立组织关系
        self.create_organization_relationships(&company_ids, &person_ids).await?;
        println!("✓ 组织关系建立完成");
        
        // 5. 创建客户关系
        self.create_customer_relationships(&company_ids, &person_ids).await?;
        println!("✓ 客户关系创建完成");
        
        // 6. 添加联系方式
        self.add_contact_information(&company_ids, &person_ids).await?;
        println!("✓ 联系方式添加完成");
        
        println!("所有示例数据加载完成！");
        Ok(())
    }

    /// 加载基础数据类型
    async fn load_basic_types(&mut self) -> Result<()> {
        // 加载Party类型
        let party_types = vec![
            ("PERSON", "个人"),
            ("PARTY_GROUP", "组织"),
            ("COMPANY", "公司"),
            ("DEPARTMENT", "部门"),
        ];
        
        for (type_id, description) in party_types {
            let party_type = PartyType {
                party_type_id: type_id.to_string(),
                parent_type_id: None,
                has_table: Some(true),
                description: Some(description.to_string()),
            };
            
            let data = party_type.to_data_row();
            let params = DataParams {
                entity_name: "PartyType".to_string(),
                data,
            };
            
            // 忽略已存在的错误
            let _ = self.client.insert_data(params).await;
        }
        
        // 加载角色类型
        let role_types = vec![
            ("EMPLOYEE", "员工"),
            ("MANAGER", "经理"),
            ("CUSTOMER", "客户"),
            ("SUPPLIER", "供应商"),
            ("SALES_REP", "销售代表"),
            ("ADMIN", "管理员"),
        ];
        
        for (role_id, description) in role_types {
            let role_type = RoleType {
                role_type_id: role_id.to_string(),
                parent_type_id: None,
                has_table: Some(false),
                description: Some(description.to_string()),
            };
            
            let data = role_type.to_data_row();
            let params = DataParams {
                entity_name: "RoleType".to_string(),
                data,
            };
            
            let _ = self.client.insert_data(params).await;
        }
        
        // 加载联系方式类型
        let contact_mech_types = vec![
            ("POSTAL_ADDRESS", "邮政地址"),
            ("TELECOM_NUMBER", "电话号码"),
            ("EMAIL_ADDRESS", "电子邮箱"),
            ("WEB_ADDRESS", "网址"),
        ];
        
        for (type_id, description) in contact_mech_types {
            let contact_type = ContactMechType {
                contact_mech_type_id: type_id.to_string(),
                parent_type_id: None,
                has_table: Some(true),
                description: Some(description.to_string()),
            };
            
            let data = contact_type.to_data_row();
            let params = DataParams {
                entity_name: "ContactMechType".to_string(),
                data,
            };
            
            let _ = self.client.insert_data(params).await;
        }
        
        // 加载联系方式用途类型
        let purpose_types = vec![
            ("PRIMARY_LOCATION", "主要地址"),
            ("BILLING_LOCATION", "账单地址"),
            ("SHIPPING_LOCATION", "收货地址"),
            ("PRIMARY_PHONE", "主要电话"),
            ("MOBILE_PHONE", "手机号码"),
            ("PRIMARY_EMAIL", "主要邮箱"),
            ("WORK_EMAIL", "工作邮箱"),
        ];
        
        for (purpose_id, description) in purpose_types {
            let purpose_type = ContactMechPurposeType {
                contact_mech_purpose_type_id: purpose_id.to_string(),
                description: Some(description.to_string()),
            };
            
            let data = purpose_type.to_data_row();
            let params = DataParams {
                entity_name: "ContactMechPurposeType".to_string(),
                data,
            };
            
            let _ = self.client.insert_data(params).await;
        }
        
        Ok(())
    }

    /// 创建示例公司
    async fn create_sample_companies(&mut self) -> Result<Vec<String>> {
        let companies = vec![
            ("科技创新有限公司", "COMPANY", "一家专注于技术创新的公司"),
            ("商贸发展集团", "COMPANY", "大型商贸集团公司"),
            ("制造业股份公司", "COMPANY", "传统制造业企业"),
        ];
        
        let mut company_ids = Vec::new();
        
        for (name, party_type, description) in companies {
            let party_id = self.party_service.create_party_group(
                name,
                party_type,
                Some(description),
                None,
                None,
                None
            ).await?;
            
            company_ids.push(party_id);
        }
        
        Ok(company_ids)
    }

    /// 创建示例个人
    async fn create_sample_persons(&mut self) -> Result<Vec<String>> {
        let persons = vec![
            ("张", "三", "先生", "zhang.san@example.com"),
            ("李", "四", "女士", "li.si@example.com"),
            ("王", "五", "先生", "wang.wu@example.com"),
            ("赵", "六", "女士", "zhao.liu@example.com"),
            ("钱", "七", "先生", "qian.qi@example.com"),
        ];
        
        let mut person_ids = Vec::new();
        
        for (last_name, first_name, title, _email) in persons {
            let party_id = self.party_service.create_person(
                Some(first_name),
                None,
                Some(last_name),
                Some(title),
                None,
                None,
                None,
                None
            ).await?;
            
            person_ids.push(party_id);
        }
        
        Ok(person_ids)
    }

    /// 建立组织关系
    async fn create_organization_relationships(
        &mut self,
        company_ids: &[String],
        person_ids: &[String]
    ) -> Result<()> {
        if company_ids.is_empty() || person_ids.is_empty() {
            return Ok(());
        }
        
        // 将前3个人员分配到第一个公司
        let company_id = &company_ids[0];
        for (i, person_id) in person_ids.iter().take(3).enumerate() {
            let role = match i {
                0 => "MANAGER",
                _ => "EMPLOYEE",
            };
            
            self.organization_service.add_organization_member(
                company_id,
                person_id,
                role,
                Some(&format!("职位{}", i + 1)),
                None
            ).await?;
        }
        
        // 将剩余人员分配到其他公司
        if company_ids.len() > 1 && person_ids.len() > 3 {
            for (i, person_id) in person_ids.iter().skip(3).enumerate() {
                let company_index = (i + 1) % (company_ids.len() - 1) + 1;
                let company_id = &company_ids[company_index];
                
                self.organization_service.add_organization_member(
                    company_id,
                    person_id,
                    "EMPLOYEE",
                    Some("普通员工"),
                    None
                ).await?;
            }
        }
        
        Ok(())
    }

    /// 创建客户关系
    async fn create_customer_relationships(
        &mut self,
        company_ids: &[String],
        person_ids: &[String]
    ) -> Result<()> {
        if company_ids.is_empty() || person_ids.is_empty() {
            return Ok(());
        }
        
        // 将第一个公司的第一个员工设为销售代表
        let sales_rep_id = &person_ids[0];
        
        // 为其他个人创建客户关系
        for person_id in person_ids.iter().skip(1) {
            self.customer_service.create_individual_customer(
                person_id,
                Some(sales_rep_id),
                None
            ).await?;
        }
        
        // 为其他公司创建企业客户关系
        for company_id in company_ids.iter().skip(1) {
            self.customer_service.create_corporate_customer(
                company_id,
                Some(sales_rep_id),
                None
            ).await?;
        }
        
        Ok(())
    }

    /// 添加联系方式
    async fn add_contact_information(
        &mut self,
        company_ids: &[String],
        person_ids: &[String]
    ) -> Result<()> {
        // 为公司添加联系方式
        for (i, company_id) in company_ids.iter().enumerate() {
            // 添加公司地址
            self.contact_service.add_postal_address(
                company_id,
                &format!("科技园区{}号", i + 1),
                Some(&format!("{}层", i + 10)),
                "深圳市",
                Some("广东省"),
                Some("518000"),
                "中国",
                "PRIMARY_LOCATION",
                true
            ).await?;
            
            // 添加公司电话
            self.contact_service.add_phone_number(
                company_id,
                Some("86"),
                Some("0755"),
                &format!("8888{:04}", i + 1000),
                None,
                "PRIMARY_PHONE",
                true
            ).await?;
            
            // 添加公司邮箱
            self.contact_service.add_email_address(
                company_id,
                &format!("info@company{}.com", i + 1),
                "PRIMARY_EMAIL",
                true
            ).await?;
        }
        
        // 为个人添加联系方式
        let person_names = vec!["zhang.san", "li.si", "wang.wu", "zhao.liu", "qian.qi"];
        
        for (i, person_id) in person_ids.iter().enumerate() {
            let name = person_names.get(i).unwrap_or(&"person");
            
            // 添加个人地址
            self.contact_service.add_postal_address(
                person_id,
                &format!("住宅小区{}栋", i + 1),
                Some(&format!("{}单元{}号", i % 3 + 1, i + 101)),
                "深圳市",
                Some("广东省"),
                Some("518000"),
                "中国",
                "PRIMARY_LOCATION",
                true
            ).await?;
            
            // 添加手机号码
            self.contact_service.add_phone_number(
                person_id,
                Some("86"),
                None,
                &format!("138{:08}", i + 10000000),
                None,
                "MOBILE_PHONE",
                true
            ).await?;
            
            // 添加个人邮箱
            self.contact_service.add_email_address(
                person_id,
                &format!("{}@example.com", name),
                "PRIMARY_EMAIL",
                true
            ).await?;
        }
        
        Ok(())
    }

    /// 清理所有示例数据
    pub async fn cleanup_sample_data(&mut self) -> Result<()> {
        println!("开始清理示例数据...");
        
        // 这里可以实现清理逻辑
        // 由于OFBiz通常使用软删除，我们可以设置thru_date来"删除"数据
        
        println!("示例数据清理完成！");
        Ok(())
    }

    /// 验证示例数据
    pub async fn verify_sample_data(&mut self) -> Result<SampleDataReport> {
        let mut report = SampleDataReport::new();
        
        // 统计Party数量
        let parties = self.party_service.get_parties(None, None, None, None).await?;
        report.party_count = parties.len();
        
        // 统计个人数量
        let persons = self.party_service.get_parties(Some("PERSON"), None, None, None).await?;
        report.person_count = persons.len();
        
        // 统计组织数量
        let organizations = self.party_service.get_parties(Some("PARTY_GROUP"), None, None, None).await?;
        report.organization_count = organizations.len();
        
        // 这里可以添加更多验证逻辑
        
        Ok(report)
    }
}

/// 示例数据报告
#[derive(Debug, Clone)]
pub struct SampleDataReport {
    pub party_count: usize,
    pub person_count: usize,
    pub organization_count: usize,
    pub relationship_count: usize,
    pub contact_count: usize,
    pub errors: Vec<String>,
}

impl SampleDataReport {
    fn new() -> Self {
        Self {
            party_count: 0,
            person_count: 0,
            organization_count: 0,
            relationship_count: 0,
            contact_count: 0,
            errors: Vec::new(),
        }
    }
    
    /// 打印报告
    pub fn print_report(&self) {
        println!("=== 示例数据报告 ===");
        println!("Party总数: {}", self.party_count);
        println!("个人数量: {}", self.person_count);
        println!("组织数量: {}", self.organization_count);
        println!("关系数量: {}", self.relationship_count);
        println!("联系方式数量: {}", self.contact_count);
        
        if !self.errors.is_empty() {
            println!("错误信息:");
            for error in &self.errors {
                println!("  - {}", error);
            }
        }
        
        println!("===================");
    }
}